﻿using System.Net;
using System.Net.Sockets;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DroidLord.Slavery;
using System.Threading;
using SharpAdbClient;
using System.Diagnostics;
using System.IO;
using DroidLord.Resource;
using MaterialSkin;
using MaterialSkin.Controls;
using System.Data.Linq;
using System.Drawing.Drawing2D;
using Svg;
using System.Text.RegularExpressions;
using DroidLord.Core;
using DroidLord.Task;
using Newtonsoft.Json.Linq;
using DroidLord.Extension;
using utils.webtime;
using DroidLord.Util;
using DroidLord.app.dy;
using Newtonsoft.Json;
using DroidLord.app.dy.data;

namespace DroidLord
{
    // MaterialForm
    public partial class MainForm : Form
    {

        public static MainForm mainForm = null;

        public string dyUrlString = "";
        public string dyUserUrlString = "";

        GraphicsPath parseSVG(string dat)
        {
            using (var s = new MemoryStream(UTF8Encoding.Default.GetBytes(dat)))
            {
                SvgDocument svgDoc = SvgDocument.Open<SvgDocument>(s, null);
                svgDoc.X = 0;
                svgDoc.Y = 0;
                var path = svgDoc.Path;
                var mat = new Matrix();
                mat.Scale(0.05f, 0.05f);
                path.Transform(mat);
                return path;
            }
        }
        void loadSettings()
        {
            lstSetting.Items.Clear();
            var conf = Program.GlobalSetting.List();
            foreach (var c in conf)
            {
                lstSetting.Items.Add(new ListViewItem(new string[] {
                    c.DisplayName,
                    c.GetDisplayType(),
                    c.Value.ToString()
                })
                { Tag = c.Name });
            }
        }
        public MainForm()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            // 搜索脚本目录
            // Program.SearchScript();
            // 加载设备和脚本
            //  reloadScriptAndDevice();
            // 加载内容素材
         
            // 加载设置
            loadSettings();

            // webBrowser1.ScriptErrorsSuppressed = true;
            // webBrowser1.Navigate("http://api.map.baidu.com/lbsapi/getpoint/index.html");
        }

        private void Contents_ResourceItemChanged(object sender, string Key)
        {
           
        }

       
        private void Slaves_ResourceItemChanged(object sender, string Key)
        {
            reloadScriptAndDevice();
            var dev = Program.Slaves.Get(Key) as SlavedDevice;
            if (dev != null)
            {
                var slave = dev.Object;
                slave.Overseer.FileDetected += Overseer_FileDetected;
                // TODO: WATCH DIR
                slave.Overseer.DirFileDetected += Overseer_DirFileDetected;
            }
        }

        private void Overseer_DirFileDetected(Slave arg1, string arg2)
        {
            //var sync = new SyncService(new AdbSocket(new IPEndPoint(IPAddress.Loopback, AdbClient.AdbServerPort)),arg1.Device);
            //var info = new FileInfo(arg2);
            //var adb = new AdbClient();
            //adb.ExecuteRemoteCommandSync(arg1.Device, $"su -c 'chmod 777 {arg2}'");

            //sync.Pull(arg2, File.Create(Program.varDir + @"\snapshot\" + info.Name),null, CancellationToken.None);
        }

        private void Overseer_FileDetected(Slave arg1, string arg2)
        {
            var lines = Regex.Split(arg2, "\r\n");
            foreach (var l in lines)
            {
                if (string.IsNullOrWhiteSpace(l)) continue;

                var groups = l.Split('|');
                var level = Core.LogLevel.Message;
                if (groups[2].ToLower() == "error")
                {
                    level = Core.LogLevel.Error;
                }
                else if (groups[2].ToLower() == "warning")
                {
                    level = Core.LogLevel.Warning;
                }
                // Example:
                // 脚本调用发生错误|无法连接远程服务器,远程服务器返回(500)|ERROR|   
                var sb = new StringBuilder();
                for (int i = 2; i < groups.Length; i++)
                {
                    sb.Append($"| {groups[i]}");
                }
                Program.Logs.WriteLog($"[设备:{arg1.Device.Serial}] {groups[0]} {sb}", groups[1], level, "remote");
            }
        }

        // 脚本有变
        private void Scripts_ResourceItemChanged(object sender, string Key)
        {
            reloadScriptAndDevice();
        }

        // 刷新列表
        void reloadScriptAndDevice()
        {

        }

        // 设备上线
        void devOnline(DeviceData dev)
        {
            //  
            DeviceManager.addOnlineDevice(dev.Serial, dev);
            // 判断设备数量
            var connected = Program.Repository.Temp["totalDev"] as int?;
            if (connected == null)
            {
                Program.Repository.Temp["totalDev"] = 1;
            }
            else
            {
                var priv = "100";// UAC.Privilege;
                var maxConnect = int.Parse(priv) * 30;
                if (connected > 8)
                {
                    return;
                }
            }

            // 添加屏幕监控
            this.Invoke((ThreadStart)(() =>
            {

                if (Program.Slaves.Get(dev.Serial) == null)
                {
                    Program.Logs.WriteLog($"设备上线:{dev.Serial}");

                    var view = new SlaveViewer();

                    view.isShowControl = true;
                    view.mainForm = this;
                    view.ResponseClick = true;
                    view.Margin = new Padding(10);
                    view.ShowMenu = true;
                    view.Parent = layoutPanel;
                    view.labelDeviceName.Parent = view;
                    layoutPanel.Controls.Add(view);
                    view.Display(dev);
                    setConnectStatusControlIsVisible(dev.Serial, true);
                    updateConnectStatus(dev.Serial, "正在初始化设备...");




                    //开启线程安装输入法
                    Dispatcher.BackgroundThread(() =>
                    {
                        Boolean isOff = AdbDeviceManager.isScreenOff(dev);
                        if (isOff)
                        {
                            AdbManager.executeShellNoRead(dev, "input keyevent POWER");
                        }

                        InputMethodManager manager = new InputMethodManager();
                        bool isUpdate = manager.isNeedUpdate(dev, "com.android.myinputmethod");
                        //MessageBox.Show("isUpdate===>" + isUpdate);
                        Boolean isInstallIme = manager.IsInstalled(dev, "com.android.myinputmethod");
                        Program.Logs.WriteLog("设备:" + dev.Serial + " IsInstalledime " + isInstallIme);
                        if (!isInstallIme || isUpdate)
                        {
                            string apkPath = PathManager.getInputMethodApkPath();

                            manager.InstallApk(dev, apkPath);

                        }
                        isInstallIme = manager.IsInstalled(dev, "com.android.myinputmethod");
                        if (isInstallIme)
                        {
                            manager.enableIme(dev, "com.android.myinputmethod/com.github.uiautomator.FastInputIME");
                            AdbManager.adbShellNoRead(dev, "am start -n  com.android.myinputmethod/com.github.uiautomator.MainActivity");
                        }
                    });

                }
            }));
        }


        public void setMainControl(Slave sv)
        {
            controlPanel.Controls.Clear();

            var view = new SlaveViewer();
            view.Left = 0;
            view.Top = 40;
            view.Width = 360 + 11;
            view.Height = 720 - 1;
            view.ResponseClick = true;
            controlPanel.Controls.Add(view);
            controlPanel.Width = view.Width;
            controlPanel.Height = view.Height;

            view.Display(sv);
            view.Invalidate();
            controlPanel.Invalidate();
        }



        //public static void StartAdbMonitor()
        //{
        //    //AdbServer adbServer = new AdbServer();

        //    var monitor = new DeviceMonitor(new AdbSocket(new System.Net.IPEndPoint(System.Net.IPAddress.Loopback, AdbClient.AdbServerPort)));

        //    monitor.DeviceConnected += Monitor_DeviceConnected;
        //    monitor.DeviceDisconnected += Monitor_DeviceDisconnected;
        //    monitor.DeviceChanged += Monitor_DeviceChanged;
        //    monitor.Start();

        //}

        private static void Monitor_DeviceChanged(object sender, DeviceDataEventArgs e)
        {
            //Events.Raise(sender, "dev_statuschange", e.Device);
            var dev = e.Device;
            // 连接后online
            if (dev.State == DeviceState.Online)
            {
                mainForm.devOnline(dev);
            }
        }

        /// <summary>
        /// 设置显示状态的控件是否可见
        /// </summary>
        /// <param name="sn"></param>
        /// <param name="text"></param>
        public void setConnectStatusControlIsVisible(String sn, Boolean isVisible)
        {
            mainForm.Invoke(new MethodInvoker(() =>
            {
                foreach (var v in mainForm.layoutPanel.Controls)
                {
                    if (v is SlaveViewer)
                    {
                        var view = v as SlaveViewer;
                        try
                        {
                            if (view.getDeviceSn().Equals(sn))
                            {
                                view.setConnectStatusControlVisible(isVisible);
                                break;
                            }
                        }
                        catch (Exception eeee)
                        {

                        }
                    }
                }
            }));
        }
        public void updateConnectStatus(String sn, String text)
        {
            mainForm.Invoke(new MethodInvoker(() =>
            {
                foreach (var v in mainForm.layoutPanel.Controls)
                {
                    if (v is SlaveViewer)
                    {
                        var view = v as SlaveViewer;
                        try
                        {
                            if (view.getDeviceSn().Equals(sn))
                            {
                                view.setConnectStatusText(text);
                                break;
                            }
                        }
                        catch (Exception eeee)
                        {

                        }
                    }
                }
            }));
        }


        private static void Monitor_DeviceDisconnected(object sender, DeviceDataEventArgs e)
        {
            // Events.Raise(sender, "adb_disconnect", e.Device);

            var dev = e.Device;
            //设备掉线了，删除缓存
            DeviceManager.removeDevice(dev.Serial);

            Program.Slaves.Remove(dev.Serial);
            // 查找屏幕监控并移除
            foreach (var v in mainForm.layoutPanel.Controls)
            {
                if (v is SlaveViewer)
                {
                    var view = v as SlaveViewer;
                    try
                    {
                        if (view.GetSlave().Device.Serial == dev.Serial)
                        {
                            var sl = view.GetSlave();
                            sl.ScreenService.Stop();
                            mainForm.Invoke((ThreadStart)(() =>
                                     mainForm.layoutPanel.Controls.Remove(view)
                            ));
                        }
                    }
                    catch (Exception eeee)
                    {

                    }
                }
            }
        }

        private static void Monitor_DeviceConnected(object sender, DeviceDataEventArgs e)
        {
            // Events.Raise(sender, "adb_connect", e.Device);

            var dev = e.Device;
            // 连接后online
            if (dev.State == DeviceState.Online)
            {
                mainForm.devOnline(dev);
            }
        }



        private static void GetTime()
        {
            while (!Program.isExist)
            {
                DateTime dt1 = GetTimeManager.GeSuNingTime();
                DateTime dt2 = GetTimeManager.GetTaoBaoTimeStamp();
                DateTime dtNow = DateTime.Now;
                int subDay = 0;
                if (dt1.Year != 2050)
                {
                    //说明时间有效
                    dtNow = dt1;
                }
                else if (dt2.Year != 2050)
                {
                    dtNow = dt2;
                }
                DateTime endTime = DateTime.Parse("2020-12-1");
                TimeSpan timeSpan = endTime.Subtract(dtNow);
                subDay = timeSpan.Days;
                if (subDay <= 0)
                {
                    //  MessageBox.Show("软件试用期已经到了");
                    System.Environment.Exit(0);


                }
                // MessageBox.Show("SuNing Time:" + dt1.ToLongDateString() + " dt2:" + dt2.ToLongDateString()+" subDay:"+subDay);
                try
                {
                    Thread.Sleep(60 * 1000);
                }
                catch (Exception eeee)
                {

                }
            }
        }


        public static void StartMyAdbMonitor()
        {

            while (!Program.isExist)
            {
                List<DeviceData> devList = AdbDeviceManager.getDevices();

                HashSet<string> devset = new HashSet<string>();
                if (DeviceManager.mIsFirstScan)
                {

                    DeviceManager.mIsFirstScan = false;
                    foreach (DeviceData devData in devList)
                    {
                        if (Program.isExist)
                        {

                            return;
                        }
                        DeviceManager.addOnlineDevice(devData.Serial, devData);

                        DeviceDataEventArgs args = new DeviceDataEventArgs(devData);
                        Monitor_DeviceChanged(null, args);
                    }
                }
                else
                {

                    foreach (DeviceData devData in devList)
                    {
                        if (Program.isExist)
                        {

                            return;
                        }
                        devset.Add(devData.Serial);
                        DeviceData mydevData = DeviceManager.getDeviceData(devData.Serial);
                        if (mydevData == null)
                        {
                            //说明没有缓存，当成是设备在线
                            DeviceManager.addOnlineDevice(devData.Serial, devData);
                            DeviceDataEventArgs args = new DeviceDataEventArgs(devData);
                            Monitor_DeviceConnected(null, args);

                        }
                    }
                    HashSet<string> cacheDevIds = DeviceManager.getOnlieDeviceIds();
                    foreach (string sn in cacheDevIds)
                    {
                        if (Program.isExist)
                        {

                            return;
                        }
                        if (!devset.Contains(sn))
                        {
                            //不包含，说明设备离线了
                            DeviceManager.removeDevice(sn);
                            DeviceData devData = new DeviceData();
                            devData.Serial = sn;
                            DeviceDataEventArgs args = new DeviceDataEventArgs(devData);
                            Monitor_DeviceDisconnected(null, args);
                        }
                    }
                }
                //每隔1秒扫描一次
                Thread.Sleep(2 * 1000);
            }
        }


        private void MainForm_Load(object sender, EventArgs e)
        {
            Program.mainFrom = this;
            //tabPageGPS.Parent = null;
          
            mainForm = this;
            this.Text = "手机管理助手V" + Config.VERSION;
            if ((bool)Program.GlobalSetting.Get("DefaultFullScreen").Value)
            {
                //MaximizeWindow(true);
                this.WindowState = FormWindowState.Maximized;
            }

            // 设备上线全局事件

           
            Dispatcher.BackgroundThread(() => StartMyAdbMonitor());
            
          
        }



        private void btnRefresh_Click(object sender, EventArgs e)
        {
            Program.Scripts.Clear();
            Program.SearchScript();
            reloadScriptAndDevice();
        }

        private void btnExecute_Click(object sender, EventArgs e)
        {

        }
        private void btnSync_Click(object sender, EventArgs e)
        {

        }

        private void layoutPanel_Scroll(object sender, ScrollEventArgs e)
        {
            foreach (var c in layoutPanel.Controls)
            {
                if (c is SlaveViewer)
                {
                    var view = c as SlaveViewer;
                    view.LayoutScrolled();
                }
            }
        }

        private void chkScript_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void chkDev_CheckedChanged(object sender, EventArgs e)
        {

        }

      

        string editContentKey = "";

      
        private void btnCoDel_Click(object sender, EventArgs e)
        {
            Program.Contents.Remove(editContentKey);
        }

        private void btnOpenImage_Click(object sender, EventArgs e)
        {
            var open = new OpenFileDialog()
            {
                Multiselect = true,
                Filter = "(*.jpg,*.png,*.jpeg,*.bmp,*.gif)|*.jpg;*.png;*.jpeg;*.bmp;*.gif| 所有文件 (*.*)|*.*"
            };
            if (open.ShowDialog() == DialogResult.OK)
            {
                var files = open.FileNames;
                foreach (var file in files)
                {
                    var pic = new PictureBox()
                    {
                        BorderStyle = BorderStyle.FixedSingle,
                        Width = 128,
                        Height = 128,
                        ImageLocation = file,
                        ContextMenuStrip = albumMenu,
                        SizeMode = PictureBoxSizeMode.Zoom
                    };
                   
                }
            }
        }

        private void lstSetting_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (lstSetting.SelectedItems.Count == 0) return;
            var selectItem = lstSetting.SelectedItems[0];
            var frm = new SettingEdit();
            frm.SetRow(Program.GlobalSetting.Get(selectItem.Tag.ToString()));
            if (frm.ShowDialog() == DialogResult.OK)
            {
                loadSettings();
                Program.screenFrame = (int)Program.GlobalSetting.Get("ScreenFrame").Value;
            }
        }

        void displayLog(List<LogItem> list)
        {

        }

        private void radioAll_CheckedChanged(object sender, EventArgs e)
        {
            showLogs();
        }

        void showLogs()
        {

        }

        private void radioWarning_CheckedChanged(object sender, EventArgs e)
        {
            showLogs();
        }

        private void radioError_CheckedChanged(object sender, EventArgs e)
        {
            showLogs();
        }

        private void radioRemote_CheckedChanged(object sender, EventArgs e)
        {
            showLogs();
        }

        private void materialFlatButton1_Click(object sender, EventArgs e)
        {

        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControlLianXiMe.SelectedIndex == 4)
            {
                showLogs();
            }
        }

        private void materialCheckBox1_CheckedChanged(object sender, EventArgs e)
        {
           
            
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            var menuItem = sender as ToolStripMenuItem;
            var menu = menuItem.Owner as ContextMenuStrip;
            var picBox = menu.SourceControl;
           
        }

        void syncContent(Content co, SlavedDevice dev)
        {
            var album = co.Album;
            var ti = co.Title;
            var cont = co.Body;

            Dispatcher.BackgroundThread(() =>
            {
                var adb = new AdbClient();
                //try
                //{
                //    adb.ExecuteRemoteCommand($"mkdir {Program.GlobalSetting.Get("ContentPath").Value}", dev.Object.Device, null);
                //}
                //catch
                //{

                //}
                //try
                //{
                //    adb.ExecuteRemoteCommand($"rm -rf {Program.GlobalSetting.Get("ContentPath").Value}/*", dev.Object.Device, null);
                //}
                //catch
                //{

                //}
                try
                {
                    adb.ExecuteRemoteCommand($"rm -rf {Program.GlobalSetting.Get("DroidAlbum").Value}/*", dev.Object.Device, null);

                }
                catch
                {

                }
                var sync = new SyncService(new AdbSocket(new IPEndPoint(IPAddress.Loopback, AdbClient.AdbServerPort)), dev.Object.Device);
                //File.WriteAllText(Program.varDir + "/tmp.dat", cont, Encoding.UTF8);
                //var stream = File.OpenRead(Program.varDir + "/tmp.dat");
                // sync.Push(stream, $"{Program.GlobalSetting.Get("ContentPath").Value}/{ti}-{co.Key}.txt", 777, DateTime.Now, CancellationToken.None);
                foreach (var pic in album)
                {
                    if (File.Exists(pic))
                    {
                        var info = new FileInfo(pic);
                        sync = new SyncService(new AdbSocket(new IPEndPoint(IPAddress.Loopback, AdbClient.AdbServerPort)), dev.Object.Device);
                        sync.Push(File.OpenRead(pic), $"{Program.GlobalSetting.Get("DroidAlbum").Value}/{Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10)}{info.Extension}", 777, DateTime.Now, null, CancellationToken.None);
                    }
                }
                // 广播相册图片改变消息
                adb.ExecuteRemoteCommand($"am broadcast -a android.intent.action.MEDIA_SCANNER_SCAN_FILE -d file://{Program.GlobalSetting.Get("DroidAlbum").Value}", dev.Object.Device, null);
                //File.Delete(Program.varDir + "/tmp.dat");
            });
        }

      

      
        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {

        }
        bool loaded = false;

        private void MainForm_Click(object sender, HtmlElementEventArgs e)
        {
            // 坐标点
            //var loc = webBrowser1.Document.GetElementById("pointInput").GetAttribute("value");
            //var pGroups = loc.Split(',');
            //if (pGroups.Length == 2)
            //{
            //    txbLocation.Text = pGroups[1] + "," + pGroups[0];
            //}
        }

        private void btLoc_Click(object sender, EventArgs e)
        {

        }

        private void btnLocation_Click(object sender, EventArgs e)
        {

        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Program.isExist = true;
            // Process.GetCurrentProcess().Kill();
            System.Environment.Exit(0);
        }

       
        private void buttonDYOpenFileDir_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(PathManager.getDYVideoDir());
        }

        private string getValue(JObject userinfo, string key)
        {
            try
            {
                return userinfo[key].ToString();
            }
            catch (Exception eee)
            {
                // MessageBox.Show(eee.ToString());
            }
            return "";
        }
        private void backgroundWorkerDYGetUserGoods_DoWork(object sender, DoWorkEventArgs e)
        {
            string ymd = MyUtils.getCurYMD();
            string realUrlString = DYGetUserGoods.getRedirectUrl(dyUserUrlString);
            if (realUrlString.Equals(""))
            {
                backgroundWorkerDYGetUserGoods.ReportProgress(-1, "任务失败,解析分享链接失败");
                return;
            }
            string[] myinfos = DYGetUserGoods.parseUserId(realUrlString);
            if (myinfos[0].Equals("") || myinfos[1].Equals(""))
            {
                backgroundWorkerDYGetUserGoods.ReportProgress(-1, "任务失败,解析分享链接失败");
                return;
            }
            string userinfo = DYGetUserGoods.getUserInfo(myinfos[0], myinfos[1]);
            if (userinfo.Equals(""))
            {
                backgroundWorkerDYGetUserGoods.ReportProgress(-1, "任务失败,获取用户信息失败");
                return;
            }

            DYUserInfoData dYUserInfoData = new DYUserInfoData().parseData(userinfo);
            if (!dYUserInfoData.uid.Equals(""))
            {
                DYDBManager.getInstance().insertUserInfo(dYUserInfoData.uid, userinfo);
            }
            backgroundWorkerDYGetUserGoods.ReportProgress(0, dYUserInfoData);
            if (dYUserInfoData.isParseOk)
            {
                backgroundWorkerDYGetUserGoods.ReportProgress(-1, "解析获取用户信息成功");
            }
            //准备抓取商品数据
            int cursor = 0;
            int index = 0;
            int pageCount = 20;
            while (true)
            {
                cursor = index * pageCount;
                String goodInfoList = DYGetUserGoods.getGoodList2(myinfos[0], myinfos[1], cursor + "", pageCount + "");
                if (goodInfoList.Equals(""))
                {
                    break;
                }
                DYUserGoodList dyUserGoodList = DYUserGoodList.parse(goodInfoList);
                if (dyUserGoodList.isResponseOk)
                {

                    DYDBManager.getInstance().insertUserGoodInfo(myinfos[0], ymd, cursor + "", goodInfoList);
                    backgroundWorkerDYGetUserGoods.ReportProgress(1, dyUserGoodList);
                    if (!dyUserGoodList.hasMore)
                    {
                        backgroundWorkerDYGetUserGoods.ReportProgress(-1, "商品抓取完成=====================");
                        break;
                    }
                    index++;
                }
                else
                {
                    backgroundWorkerDYGetUserGoods.ReportProgress(-1, "获取用户商品列表信息失败");
                    break;
                }
                Thread.Sleep(10 * 1000);
            }

        }

        private void setDataGridViewCellData(DataGridView dataGridView, int rowIndex, int cellIndex, String value)
        {
            //dataGridViewDYUserInfo.Rows[index].Cells[0].Value = dYUserInfoData.nickName;
        }

        private void controlPanel_Paint(object sender, PaintEventArgs e)
        {

        }

        public void panelControl_MouseMove(object sender, MouseEventArgs e)
        {
            showInputMethod(new Point(e.X + 20, e.Y + 20), true);
        }

        private void showInputMethod(Point showPoint, Boolean isUsePoint)
        {
            if (isUsePoint)
            {
                alphaBlendTextBoxInputText.Visible = true;
                alphaBlendTextBoxInputText.Location = showPoint;
                alphaBlendTextBoxInputText.Focus();
                return;
            }
            else
            {
                alphaBlendTextBoxInputText.Visible = false;
            }
        }

        private void alphaBlendTextBoxInputText_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && Program.totalControlViewer != null)
            {
                try
                {
                    String text = alphaBlendTextBoxInputText.Text + "";
                    if (!text.Equals(""))
                    {
                        if (Program.totalControlViewer.GetSlave().Device != null)
                        {
                            if (false)
                            // if (checkBoxControlAll.Checked)
                            {
                                foreach (var v in MainForm.mainForm.layoutPanel.Controls)
                                {
                                    if (v is SlaveViewer)
                                    {
                                        var view = v as SlaveViewer;
                                        view.GetSlave().Manipulation.inputText(text);
                                    }
                                }

                            }
                            else
                            {
                                Program.totalControlViewer.GetSlave().Manipulation.inputText(text);
                            }


                        }
                        //screencommandQueue.Enqueue("am|broadcast|-a|ADB_INPUT_TEXT|--es|msg|" + text.Trim() + "\n");
                        alphaBlendTextBoxInputText.Text = "";
                        alphaBlendTextBoxInputText.SelectionStart = 0;
                    }
                }
                catch (Exception eeeee)
                {

                }
            }
        }

        private void alphaBlendTextBoxInputText_TextChanged(object sender, EventArgs e)
        {

        }

        private void buttonWakeup_Click(object sender, EventArgs e)
        {
            if (Program.totalControlViewer == null)
            {
                MessageBox.Show("还未设置主控设备,请初始化主控设备");
                return;
            }
            if (checkBoxControlAll.Checked)
            {
                foreach (var v in MainForm.mainForm.layoutPanel.Controls)
                {
                    if (v is SlaveViewer)
                    {
                        var view = v as SlaveViewer;
                        view.GetSlave().Manipulation.wakeUp();
                    }
                }
                return;
            }
            if (Program.totalControlViewer != null)
            {
                Program.totalControlViewer.GetSlave().Manipulation.wakeUp();
            }
        }

        private void buttonUp_Click(object sender, EventArgs e)
        {
            if (Program.totalControlViewer == null)
            {
                MessageBox.Show("还未设置主控设备,请初始化主控设备");
                return;
            }
            if (checkBoxControlAll.Checked)
            {
                foreach (var v in MainForm.mainForm.layoutPanel.Controls)
                {
                    if (v is SlaveViewer)
                    {
                        var view = v as SlaveViewer;
                        view.GetSlave().Manipulation.buttonUp();
                    }
                }
                return;
            }
            if (Program.totalControlViewer != null)
            {
                Program.totalControlViewer.GetSlave().Manipulation.buttonUp();
            }
        }

        private void buttonClearText_Click(object sender, EventArgs e)
        {
            if (Program.totalControlViewer == null)
            {
                MessageBox.Show("还未设置主控设备,请初始化主控设备");
                return;
            }
            if (checkBoxControlAll.Checked)
            {
                foreach (var v in MainForm.mainForm.layoutPanel.Controls)
                {
                    if (v is SlaveViewer)
                    {
                        var view = v as SlaveViewer;
                        view.GetSlave().Manipulation.ClearText();
                    }
                }
                return;
            }
            if (Program.totalControlViewer != null)
            {
                Program.totalControlViewer.GetSlave().Manipulation.ClearText();
            }
        }

        private void buttonHome_Click(object sender, EventArgs e)
        {
            if (Program.totalControlViewer == null)
            {
                MessageBox.Show("还未设置主控设备,请初始化主控设备");
                return;
            }
            if (checkBoxControlAll.Checked)
            {
                foreach (var v in MainForm.mainForm.layoutPanel.Controls)
                {
                    if (v is SlaveViewer)
                    {
                        var view = v as SlaveViewer;
                        view.GetSlave().Manipulation.Keypress(Slavery.DroidKey.HOME);
                    }
                }
                return;
            }
            if (Program.totalControlViewer != null)
            {
                Program.totalControlViewer.GetSlave().Manipulation.Keypress(Slavery.DroidKey.HOME);
            }
        }

        private void buttonLeft_Click(object sender, EventArgs e)
        {
            if (Program.totalControlViewer == null)
            {
                MessageBox.Show("还未设置主控设备,请初始化主控设备");
                return;
            }
            if (checkBoxControlAll.Checked)
            {
                foreach (var v in MainForm.mainForm.layoutPanel.Controls)
                {
                    if (v is SlaveViewer)
                    {
                        var view = v as SlaveViewer;
                        view.GetSlave().Manipulation.buttonLeft();
                    }
                }
                return;
            }
            if (Program.totalControlViewer != null)
            {
                Program.totalControlViewer.GetSlave().Manipulation.buttonLeft();
            }
        }

        private void buttonRight_Click(object sender, EventArgs e)
        {
            if (Program.totalControlViewer == null)
            {
                MessageBox.Show("还未设置主控设备,请初始化主控设备");
                return;
            }
            if (checkBoxControlAll.Checked)
            {
                foreach (var v in MainForm.mainForm.layoutPanel.Controls)
                {
                    if (v is SlaveViewer)
                    {
                        var view = v as SlaveViewer;
                        view.GetSlave().Manipulation.buttonRight();
                    }
                }
                return;
            }
            if (Program.totalControlViewer != null)
            {
                Program.totalControlViewer.GetSlave().Manipulation.buttonRight();
            }
        }

        private void buttonBack_Click(object sender, EventArgs e)
        {
            if (Program.totalControlViewer == null)
            {
                MessageBox.Show("还未设置主控设备,请初始化主控设备");
                return;
            }
            if (checkBoxControlAll.Checked)
            {
                foreach (var v in MainForm.mainForm.layoutPanel.Controls)
                {
                    if (v is SlaveViewer)
                    {
                        var view = v as SlaveViewer;
                        view.GetSlave().Manipulation.Keypress(Slavery.DroidKey.BACK);
                    }
                }
                return;
            }
            if (Program.totalControlViewer != null)
            {
                Program.totalControlViewer.GetSlave().Manipulation.Keypress(Slavery.DroidKey.BACK);
            }
        }

        private void buttonDown_Click(object sender, EventArgs e)
        {
            if (Program.totalControlViewer == null)
            {
                MessageBox.Show("还未设置主控设备,请初始化主控设备");
                return;
            }
            if (checkBoxControlAll.Checked)
            {
                foreach (var v in MainForm.mainForm.layoutPanel.Controls)
                {
                    if (v is SlaveViewer)
                    {
                        var view = v as SlaveViewer;
                        view.GetSlave().Manipulation.buttonDown();
                    }
                }
                return;
            }
            if (Program.totalControlViewer != null)
            {
                Program.totalControlViewer.GetSlave().Manipulation.buttonDown();
            }
        }

        private void buttonPower_Click(object sender, EventArgs e)
        {
            if (Program.totalControlViewer == null)
            {
                MessageBox.Show("还未设置主控设备,请初始化主控设备");
                return;
            }
            if (checkBoxControlAll.Checked)
            {
                foreach (var v in MainForm.mainForm.layoutPanel.Controls)
                {
                    if (v is SlaveViewer)
                    {
                        var view = v as SlaveViewer;
                        view.GetSlave().Manipulation.Keypress(Slavery.DroidKey.POWER);
                    }
                }
                return;
            }
            if (Program.totalControlViewer != null)
            {
                Program.totalControlViewer.GetSlave().Manipulation.Keypress(Slavery.DroidKey.POWER);
            }
        }

        private void checkBoxControlAll_CheckedChanged(object sender, EventArgs e)
        {
            Program.isOpenTotalControl = checkBoxControlAll.Checked;
            if(Program.totalControlViewer!=null)
            {
                Program.totalControlViewer.isTotalControl = checkBoxControlAll.Checked;
                Program.totalControlViewer.isControlViewer = checkBoxControlAll.Checked;
            }
        }

        private void buttonInputText_Click(object sender, EventArgs e)
        {
            if (Program.totalControlViewer == null)
            {
                MessageBox.Show("还未设置主控设备,请初始化主控设备");
                return;
            }
            String text = textBoxInputText.Text + "";
            if (!text.Equals(""))
            {

                if (checkBoxControlAll.Checked)
                {
                    foreach (var v in MainForm.mainForm.layoutPanel.Controls)
                    {
                        if (v is SlaveViewer)
                        {
                            var view = v as SlaveViewer;
                            view.GetSlave().Manipulation.inputText(text);
                        }
                    }

                }
                else
                {
                    Program.totalControlViewer.GetSlave().Manipulation.inputText(text);
                }
                textBoxInputText.Text = "";
                textBoxInputText.SelectionStart = 0;
            }
        }

        private void buttonSwitchIme_Click(object sender, EventArgs e)
        {
            if (Program.totalControlViewer == null)
            {
                MessageBox.Show("还未设置主控设备,请初始化主控设备");
                return;
            }
            if (checkBoxControlAll.Checked)
            {
                foreach (var v in MainForm.mainForm.layoutPanel.Controls)
                {
                    if (v is SlaveViewer)
                    {
                        var view = v as SlaveViewer;
                        view.GetSlave().Manipulation.switchIme();
                    }
                }
                return;
            }
            if (Program.totalControlViewer != null)
            {
                Program.totalControlViewer.GetSlave().Manipulation.switchIme();
            }
        }

        private void albumMenu_Opening(object sender, CancelEventArgs e)
        {

        }

        private void tabPage1_Click(object sender, EventArgs e)
        {

        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void pictureBoxWX_Click(object sender, EventArgs e)
        {

        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void tabPage7_Click(object sender, EventArgs e)
        {

        }

        private void pictureBoxZhiFuBao_Click(object sender, EventArgs e)
        {

        }

        private void tabPagePic_Click(object sender, EventArgs e)
        {

        }

        private void txbCoTitle_TextChanged(object sender, EventArgs e)
        {

        }

        private void txbContent_TextChanged(object sender, EventArgs e)
        {

        }

        private void materialLabel1_Click(object sender, EventArgs e)
        {

        }

        private void contentAlbum_Paint(object sender, PaintEventArgs e)
        {

        }

        private void tabPageSystemSettings_Click(object sender, EventArgs e)
        {

        }

        private void lstSetting_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void tabPageListDevice_Click(object sender, EventArgs e)
        {

        }

        private void splitContainerControlDevices_SplitterMoved(object sender, SplitterEventArgs e)
        {

        }

        private void groupBox6_Enter(object sender, EventArgs e)
        {

        }

        private void panelControl_Paint(object sender, PaintEventArgs e)
        {

        }

        private void layoutPanel_Paint(object sender, PaintEventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void tabPageDY_Click(object sender, EventArgs e)
        {

        }

        private void tabControl2_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void tabPage2_Click(object sender, EventArgs e)
        {

        }

        private void groupBox2_Enter(object sender, EventArgs e)
        {

        }

        private void groupBox3_Enter(object sender, EventArgs e)
        {

        }

        private void textBoxDYDownloadResult_TextChanged(object sender, EventArgs e)
        {

        }

        private void buttonDYPlayVideo_Click(object sender, EventArgs e)
        {

        }

        private void textBoxDYVideoUrl_TextChanged(object sender, EventArgs e)
        {

        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void tabPage3_Click(object sender, EventArgs e)
        {

        }

        private void tabControl3_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void tabPage5_Click(object sender, EventArgs e)
        {

        }

        private void dataGridViewDYUserInfo_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void tabPage4_Click(object sender, EventArgs e)
        {

        }

        private void dataGridViewDYUserGoodList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void tabPage6_Click(object sender, EventArgs e)
        {

        }

        private void groupBox5_Enter(object sender, EventArgs e)
        {

        }

        private void richTextBoxDYShowGetUserLog_TextChanged(object sender, EventArgs e)
        {

        }

        private void groupBox4_Enter(object sender, EventArgs e)
        {

        }

        private void label4_Click(object sender, EventArgs e)
        {

        }

        private void comboBoxDYUserUrl_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void statusStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void toolStripDropDownButton1_Click(object sender, EventArgs e)
        {

        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {

        }

        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {

        }

        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {

        }

        private void toolStripMenuItem5_Click(object sender, EventArgs e)
        {

        }

        private void toolStripMenuItem6_Click(object sender, EventArgs e)
        {

        }

        private void toolStripMenuItem7_Click(object sender, EventArgs e)
        {

        }

        private void tabControl4_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void tabPage8_Click(object sender, EventArgs e)
        {

        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void tabPage9_Click(object sender, EventArgs e)
        {

        }

        private void groupBox7_Enter(object sender, EventArgs e)
        {

        }

        private void textBoxInputText_TextChanged(object sender, EventArgs e)
        {

        }

        private void MainForm_SizeChanged(object sender, EventArgs e)
        {
            //MessageBox.Show(""+this.WindowState);
            if(Program.totalControlViewer==null)
            {
                return;
            }
            Slave myslave = Program.totalControlViewer.GetSlave();
            if(1>0)
            {
                Program.mainFrom.createTotalControlView(myslave);
                return;
            }

            int mywidht = controlPanel.Width;
            if (this.WindowState == FormWindowState.Maximized)
            {


                Program.mainFrom.panelControl.Width = 240;// 240;
                Program.mainFrom.panelControl.Height = 480;// 480;

                Program.totalControlViewer.Width = Program.mainFrom.panelControl.Width;
                Program.totalControlViewer.Height = Program.mainFrom.panelControl.Height;
                Program.mainFrom.panelControl.Parent = Program.mainFrom.controlPanel;
                Program.mainFrom.panelControl.BringToFront();
                if (mywidht > Program.totalControlViewer.Width)
                {
                    int subWidth = mywidht - Program.totalControlViewer.Width;
                    int halfWidth = subWidth / 2;
                    panelControl.SetBounds(controlPanel.Location.X + halfWidth, controlPanel.Location.Y + 1, panelControl.Width, panelControl.Height);
                }
                Program.mainFrom.panelControl.Invalidate();
            }
            else if (this.WindowState == FormWindowState.Normal)
            {
                Program.mainFrom.panelControl.Width = 240;
                Program.mainFrom.panelControl.Height = 480;
                Program.totalControlViewer.Width = Program.mainFrom.panelControl.Width;
                Program.totalControlViewer.Height = Program.mainFrom.panelControl.Height;

                Program.mainFrom.panelControl.Parent = Program.mainFrom.controlPanel;
                Program.mainFrom.panelControl.BringToFront();
                if (mywidht > Program.totalControlViewer.Width)
                {
                    int subWidth = mywidht - Program.totalControlViewer.Width;
                    int halfWidth = subWidth / 2;
                    panelControl.SetBounds(controlPanel.Location.X + halfWidth, controlPanel.Location.Y + 1, panelControl.Width, panelControl.Height);
                }
                Program.mainFrom.panelControl.Invalidate();
            }
        }


        public void createTotalControlView(Slave slave)
        {

           
            if (Program.totalControlViewer != null)
            {
                Program.totalControlViewer.removeFrameArrived();
                Program.totalControlViewer = null;
            }
            var view = new SlaveViewer();

            view.isTotalControl = true;
            view.设为主控ToolStripMenuItem.Visible = false;
            view.setConnectStatusControlVisible(false);
            view.ResponseClick = true;

            view.Dock = DockStyle.Fill;
            view.screenFormControl = null;
            view.mainForm = Program.mainFrom;
            if (Program.mainFrom.WindowState == FormWindowState.Maximized)
            {
                Program.mainFrom.panelControl.Width = 300;
                Program.mainFrom.panelControl.Height = 600;
            }
            else
            {
                Program.mainFrom.panelControl.Width = 240;
                Program.mainFrom.panelControl.Height = 480;
            }
            Program.mainFrom.panelControl.Controls.Add(view);

            Program.mainFrom.panelControl.Parent = Program.mainFrom.controlPanel;
            Program.mainFrom.panelControl.BringToFront();

            view.Left = Program.mainFrom.panelControl.Left;
            view.Top = Program.mainFrom.panelControl.Top;
            view.Width = Program.mainFrom.panelControl.Width;
            view.Height = Program.mainFrom.panelControl.Height;

            view.BringToFront();

            view.Display(slave);
            Program.mainFrom.alphaBlendTextBoxInputText.Parent = view;
            view.BringToFront();
            view.Invalidate();

            Program.totalControlViewer = view;

            int mywidth = Program.mainFrom.controlPanel.Width;
            if (mywidth > Program.totalControlViewer.Width)
            {
                int subWidth = mywidth - Program.totalControlViewer.Width;
                int halfWidth = subWidth / 2;
                Program.mainFrom.panelControl.SetBounds(Program.mainFrom.controlPanel.Location.X + halfWidth, Program.mainFrom.controlPanel.Location.Y + 1, Program.mainFrom.panelControl.Width, Program.mainFrom.panelControl.Height);
            }



        }

        private void timerDetectAdb_Tick(object sender, EventArgs e)
        {
            List<String> processList = PortUseKiller.getPortUseProcessList(5037);
            MessageBox.Show(""+processList.ToString());
        }
    }
}